<template>
  <div v-loading="loading" element-loading-text="加载中" class="config-edit">
    <div v-show="!showPicDetail">
      <div class="bread-box but20">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item class="btn-green" style=" color: #3DC094;" @click.native="handleBack">资源饰品类配置</el-breadcrumb-item>
          <el-breadcrumb-item>{{ formData.configCode ? '编辑' : '新增' }}</el-breadcrumb-item>
        </el-breadcrumb>
        <div>
          <el-button size="mini" @click="handleBack">取消</el-button>
          <el-button type="primary" size="mini" @click="clickNextStep">确认</el-button>
        </div>
      </div>
      <div style="margin-top:20px">
        <el-form ref="rulesForm" :model="formData" :rules="formRules" label-width="140px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="产品配置单:" prop="configCode">
                <span>{{ formData.configCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="产品配置类型:" prop="proConfigType">
                <el-select v-model="formData.proConfigType" placeholder="请选择" @change="changeConfigType">
                  <el-option v-for="item in configTypeList" :key="item.dictCode" :label="item.dictName" :value="item.dictCode" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item v-if="showProDetail" label="产品分类明细:" prop="classDetail" :rules="[{ required: formData.proConfigType === 'ACCESSORY', message: '请选择产品分类明细' }]">
                <c-dict-select v-model="formData.classDetail" dict-type-code="CLASS_DETAIL" placeholder="产品分类明细" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item v-if="showSendType" label="发货方式:" prop="deliveryMethod" :rules="[{ required: formData.proConfigType === 'RESOURCES', message: '请选择发货方式' }]">
                <c-dict-select v-model="formData.deliveryMethod" dict-type-code="DELIVERY_METHOD" placeholder="发货方式" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item v-if="formData.proConfigType" label="门店建设项目号:" prop="constData">
                <input-with-dialog
                  v-model="formData.constData"
                  placeholder="门店建设项目号"
                  :props="{label:'constCode',value:'constCode'}"
                  param-field="keyWord"
                  :focus-query="true"
                  :config="constCodeConfig"
                  @change="constCodeChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属门店编码:" prop="shopCode">
                <span>{{ formData.shopCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属门店名称:" prop="shopName">
                <span>{{ formData.shopName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属客户编码:" prop="clientCode">
                <span>{{ formData.clientCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属客户名称:" prop="clientName">
                <span>{{ formData.clientName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属办事处:" prop="officeName">
                <span>{{ formData.officeName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item v-if="formData.proConfigType && formData.constCode" label="产品配置人员:" prop="proConfiguratorCode">
                <!-- <input-with-dialog
                v-model="formData.staff"
                :props="{label:'personnelName',value:'personnelCode'}"
                :multiple="false"
                :focus-query="true"
                :config="configuratorConfig"
                @change="configuratorChange"
              /> -->
                <el-select v-model="formData.proConfiguratorCode" placeholder="请选择" @change="configuratorChange">
                  <el-option v-for="item in configuratorList" :key="item.personnelCode" :label="item.personnelName" :value="item.personnelCode" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="创建时间:" prop="createTime">
                <span>{{ formData.createTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="创建人:" prop="createBy">
                <span>{{ formData.createBy }}</span>
              </el-form-item>
            </el-col>
            <el-col v-if="formData.configCode" :span="8">
              <el-form-item label="修改人:" prop="lastUpdateBy">
                <span>{{ formData.lastUpdateBy }}</span>
              </el-form-item>
            </el-col>
            <el-col v-if="formData.configCode" :span="8">
              <el-form-item label="修改时间:" prop="lastUpdateTime">
                <span>{{ formData.lastUpdateTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关联图纸总面积:" prop="picTotalArea">
                <span>{{ formData.picTotalArea }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <c-section title="关联图纸信息">
        <div class="btn-container">
          <el-button type="primary" @click="choicePicTask">关联图纸</el-button>
          <el-button type="primary" @click="delTableData">删行</el-button>
        </div>
        <RelevanceDrawing v-if="showPicDlg" ref="relevanceDrawing" :visible.sync="showPicDlg" :detail-data="activedData" @success="getPicTableData" />
        <c-table-box :data="tableData" checkbox :table-config="tableConfig" @selection-change="selectionChangeHandle" />
      </c-section>
    </div>
    <detail v-if="showPicDetail" :shop-config-data="rowId" page-flag="shopConfig" :page-show.sync="showPicDetail" @goBack="backDetail" />
  </div>
</template>
<script>
import RelevanceDrawing from '../../task/handle/components/relevanceDrawing.vue'
import detail from '../../../shopDrawing/management/detail.vue'
// import ReDraw from './components/reDraw'
import { getDictByPatchType } from '@/api/dataDict'
import { submitConfigTable, queryConfigurator } from '@/api/proConfig'
import { getUserInfo } from '@/utils/auth'
import { getAreaData } from '../../task/components/index'
export default {
  name: 'DecorationConfigEdit',
  components: {
    RelevanceDrawing,
    detail
    // ReDraw
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      rowId: '',
      showPicDetail: false,
      loading: false,
      showPicDlg: false,
      showSendType: false,
      showProDetail: false,
      areaList: [],
      configuratorList: [],
      configTypeList: [],
      designRangeList: [],
      decorationTypeList: [],
      designSpaceList: [],
      designBizTypeList: [],
      activedData: {},
      tableData: [],
      tableSelected: [],
      formData: {
        constData: [],
        staff: []
      },
      formRules: {
        proConfigType: [{ required: true, message: '请选择产品配置类型' }],
        constData: [{ required: true, message: '请选择门店建设号' }],
        proConfiguratorCode: [{ required: true, message: '请选择产品配置人员' }]
      },
      constCodeConfig: {
        title: '门店建设号',
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/shopConstruct/allPage`,
        setting: [
          {
            prop: 'shopCode',
            title: '门店编码'
          },
          {
            prop: 'shopName',
            title: '门店名称'
          },
          {
            prop: 'constCode',
            title: '门店建设号'
          }
        ]
      },
      configuratorConfig: {
        title: '产品配置人员',
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/configPersonnelAndOffice/page`,
        setting: [
          {
            prop: 'personnelCode',
            title: '编码'
          },
          {
            prop: 'personnelName',
            title: '名称'
          }
        ]
      },
      tableConfig: {
        hideFuncBar: true,
        setting: [
          {
            prop: 'picTaskCode',
            label: '图纸编码',
            minWidth: 100,
            className: 'btn-green',
            isButton: true,
            clickFun: this.toPicDetail
          },
          {
            prop: 'picType',
            label: '图纸类型',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'PIC_TYPE'
            },
            minWidth: 100
          },
          {
            prop: 'designRange',
            label: '设计范围',
            minWidth: 100,
            render: (creat, row) => {
              if (!row.designRange) {
                return
              }
              let list = []
              if (typeof (row.designRange) === 'string') {
                list = row.designRange.split(',')
              } else {
                list = row.designRange
              }
              const arr = []
              this.designRangeList.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            }
          },
          {
            prop: 'decorationType',
            label: '装修形式',
            minWidth: 100,
            render: (creat, row) => {
              if (!row.decorationType) {
                return
              }
              let list = []
              if (typeof (row.decorationType) === 'string') {
                list = row.decorationType.split(',')
              } else {
                list = row.decorationType
              }
              const arr = []
              this.decorationTypeList.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            }
          },
          {
            prop: 'designSpace',
            label: '设计区域',
            minWidth: 100,
            render: (creat, row) => {
              if (!row.designSpace) {
                return
              }
              let list = []
              if (typeof (row.designSpace) === 'string') {
                list = row.designSpace.split(',')
              } else {
                list = row.designSpace
              }
              const arr = []
              this.areaList.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            }
          },
          {
            prop: 'designBizType',
            label: '设计业务类型',
            minWidth: 140,
            render: (creat, row) => {
              if (!row.designBizType) {
                return
              }
              let list = []
              if (typeof (row.designBizType) === 'string') {
                list = row.designBizType.split(',')
              } else {
                list = row.designBizType
              }
              const arr = []
              this.designBizTypeList.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            }
          },
          {
            prop: 'picTotalArea',
            label: '设计总面积',
            minWidth: 120
          },
          // {
          //   prop: 'finishedProductAreaSummary',
          //   label: '成品业务面积汇总',
          //   minWidth: 100
          // },
          {
            prop: 'softwareSumArea',
            label: '软体区面积',
            minWidth: 120
          },
          {
            prop: 'suiteSumArea',
            label: '套房区面积',
            minWidth: 120
          },
          {
            prop: 'haveEAndC',
            label: '是否含成融定',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            },
            minWidth: 140
          },
          {
            prop: 'eandCArea',
            label: '成融定面积',
            minWidth: 120
          },
          {
            prop: 'newBusinessAreaSummary',
            label: '新业务面积汇总',
            minWidth: 100
          },
          {
            prop: 'expectEndTime',
            label: '预计设计完成时间',
            minWidth: 140
          },
          {
            prop: 'designUnitName',
            label: '设计单位',
            minWidth: 100
          },
          {
            prop: 'designerName',
            label: '设计师',
            minWidth: 100
          },
          {
            prop: 'schedule',
            label: '图纸进度',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'PIC_DESIGN_SCHEDULE'
            },
            minWidth: 100
          },
          {
            prop: 'state',
            label: '图纸状态',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'PIC_DESIGN_STATE'
            },
            minWidth: 100
          }
        ]
      }
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    // 选中行id
    selectedIds() {
      return this.selectedRows.map(row => {
        return row.id
      })
    }
  },
  async created() {
    // this.$set(this.formData, 'staff', [])
    const type = ['RESOURCES', 'ACCESSORY']
    await this.getDictByPatchTypeAll(['PRO_CONFIG_TYPE', 'DECORATION_RANGE', 'DECORATION_FORM', 'BELONG_REGION', 'BIZ_TYPE']).then(res => {
      this.configTypeList = res.PRO_CONFIG_TYPE.filter(item => type.includes(item.dictCode))
      this.designRangeList = res.DECORATION_RANGE // 设计范围
      this.decorationTypeList = res.DECORATION_FORM // 装修形式
      this.designSpaceList = res.BELONG_REGION // 设计区域
      this.designBizTypeList = res.BIZ_TYPE // 设计业务类型
    })
    // if (this.$route.params.configCode) {
    //   getProConfigEditData(this.$route.params.id).then(res => {
    //     if (res.success && res.data) {
    //       this.formData = res.data
    //       this.tableData = this.formData.designPictureDtos
    //       if (this.tableData.length) {
    //         let area = 0
    //         this.tableData.forEach(item => {
    //           area = area + item.picTotalArea
    //         })
    //         this.formData.picTotalArea = area
    //       }
    //     }
    //   })
    //   return
    // }
    this.areaList = await getAreaData()
    const { userName } = getUserInfo()
    this.formData.createBy = userName
    const date = new Date()
    const year = date.getFullYear()
    const month = this.addZero(date.getMonth() + 1)
    const day = this.addZero(date.getDate())
    const hour = this.addZero(date.getHours())
    const minute = this.addZero(date.getMinutes())
    const second = this.addZero(date.getSeconds())
    this.formData.createTime = `${year}-${month}-${day} ${hour}:${minute}:${second}`
  },
  methods: {
    // 获取数据字典
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    selectionChangeHandle(rows) {
      this.tableSelected = rows
    },
    // 选择产品配置类型
    changeConfigType(value) {
      if (value === 'RESOURCES') {
        this.showSendType = true
        this.showProDetail = false
      } else if (value === 'ACCESSORY') {
        this.showProDetail = true
        this.showSendType = false
      }
    },
    // 选择门店建设项目号
    constCodeChange(data) {
      this.formData.constCode = data[0].constCode
      this.formData.shopName = data[0].shopName
      this.formData.shopCode = data[0].shopCode
      this.formData.clientName = data[0].clientName
      this.formData.clientCode = data[0].clientCode
      this.formData.officeName = data[0].officeName
      this.formData.officeCode = data[0].officeCode
      // this.formData.proConfiguratorName = ''
      // this.formData.proConfiguratorCode = ''
      // this.formData.staff = []
      this.getConfigurator()
    },
    // 获取产品配置人
    getConfigurator() {
      let personnelPost = 'A'
      if (this.formData.proConfigType === 'ACCESSORY') {
        personnelPost = 'B'
      }
      const otherFilter = [{ 'id': 'officeCode', 'property': 'officeCode', 'operator': '=', 'value': this.formData.officeCode },
        { 'id': 'personnelPost', 'property': 'personnelPost', 'operator': '=', 'value': personnelPost },
        { 'id': 'enable', 'property': 'enable', 'operator': '=', 'value': '1' }]
      const dataForm = new FormData()
      dataForm.append('pageFalg', false)
      dataForm.append('filtersRaw', JSON.stringify(otherFilter))
      queryConfigurator(dataForm).then(res => {
        if (res.success && res.data && res.data.records) {
          this.configuratorList = res.data.records
          if (this.configuratorList.length) {
            this.configuratorChange(this.configuratorList[0].personnelCode)
            this.$set(this.formData, 'proConfiguratorCode', this.configuratorList[0].personnelCode)
            this.$set(this.formData, 'proConfiguratorName', this.configuratorList[0].personnelName)
            this.$nextTick(() => {
              this.$refs.rulesForm.clearValidate()
            })
          }
        }
      })
    },
    // 选择产品配置人
    configuratorChange(data) {
      // if (data && data.length) {
      //   this.formData.proConfiguratorName = data[0].personnelName
      //   this.formData.proConfiguratorCode = data[0].personnelCode
      // }
      this.configuratorList.forEach(item => {
        if (item.personnelCode === data) {
          this.formData.proConfiguratorName = item.personnelName
        }
      })
    },
    // 关联图纸
    choicePicTask() {
      this.$refs.rulesForm.validate((validate) => {
        if (validate) {
          this.activedData = this.formData
          this.showPicDlg = true
        }
      })
    },
    // 接收选择的关联图纸
    getPicTableData(data) {
      if (!this.tableData.length) {
        this.tableData = [...data]
        let area = 0
        this.tableData.forEach(item => {
          if (item.picTotalArea) {
            area = area + (isNaN(Number(item.picTotalArea)) ? 0 : Number(item.picTotalArea))
          }
        })
        this.$set(this.formData, 'picTotalArea', area)
      } else {
        const arr1 = []
        const arr2 = []
        data.forEach(item => {
          const flag = this.tableData.some(v => v.picTaskCode === item.picTaskCode)
          if (flag) {
            arr1.push(item)
          } else {
            arr2.push(item)
          }
        })
        if (arr1.length > 0) {
          const msgArr = arr1.map(item => item.picTaskCode)
          this.$message.warning(`编码为${msgArr.toString()}的图纸已存在`)
        }
        this.tableData = [...this.tableData, ...arr2]
        if (!arr2.length) return
        let area = 0
        this.tableData.forEach(item => {
          if (item.picTotalArea) {
            area = area + (isNaN(Number(item.picTotalArea) ? 0 : Number(item.picTotalArea)))
          }
        })
        this.$set(this.formData, 'picTotalArea', area)
      }
    },
    // 删行
    delTableData() {
      if (!this.tableSelected.length) {
        this.$message.warning('请选择【删除】项')
        return
      }
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.tableData.length === this.tableSelected.length) {
          this.tableData = []
          return
        }
        const tmpData = this.tableData.filter(row => {
          const index = this.tableSelected.findIndex(v => v.picTaskCode === row.picTaskCode)
          return index === -1
        })
        this.tableData = tmpData
        this.tableSelected = []
        this.getPicTotalArea()
        this.$refs.refTable.clearSelection()
      })
    },
    // 计算关联图纸面积
    getPicTotalArea() {
      let area = 0
      this.tableData.forEach(item => {
        area = area + (isNaN(Number(item.picTotalArea)) ? 0 : Number(item.picTotalArea))
      })
      this.formData.picTotalArea = area
    },
    // 格式化时间
    addZero(num) {
      if (num < 10) {
        return ('0' + num)
      }
      return num
    },
    // 查看图纸详情
    toPicDetail(row) {
      this.rowId = row
      this.showPicDetail = true
    },
    // 返回配置详情
    backDetail() {
      this.showPicDetail = false
    },
    // 返回
    handleBack() {
      this.clearForm()
      this.$store.dispatch('views/goBack')
    },
    clearForm(done) {
      this.formData = {
        constData: [],
        staff: []
      }
      this.$refs.rulesForm && this.$refs.rulesForm.clearValidate()
      done && done()
    },
    // 确定
    clickNextStep() {
      this.$refs.rulesForm.validate(validate => {
        if (validate) {
          if (!this.tableData.length) {
            this.$message.warning('请关联图纸')
            return
          }
          this.loading = true
          const picIds = this.tableData.map(item => item.id)
          this.formData.picIds = picIds
          this.formData.isValid = 1
          submitConfigTable(this.formData).then(res => {
            if (res.success) {
              this.$message.success('操作成功')
              this.handleBack()
            }
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.but20{ margin-bottom: 20px;}
.el-breadcrumb__inner .btn-green{
    color: #3DC094;
}
/deep/.el-breadcrumb__inner{
  color: $qup-color-primary;
}
</style>
